// 类型定义和上下文创建
import { createContext, useContext } from 'react';

import { DARK_CLASS } from '@/constants/app';

import type { ThemeModeType } from 'ahooks/lib/useTheme';

/**
 * ThemeContextType 定义主题上下文的结构
 * @typedef {Object} ThemeContextType
 * @property {boolean} darkMode - 当前是否为暗模式
 * @property {function} setThemeScheme - 设置主题方案的函数
 * @property {ThemeModeType} themeScheme - 当前主题方案
 * @property {function} toggleThemeScheme - 切换主题方案的函数
 */
export type ThemeContextType = {
	darkMode: boolean;
	setThemeScheme: (themeScheme: ThemeModeType) => void;
	themeScheme: ThemeModeType;
	toggleThemeScheme: () => void;
};

/**
 * ThemeContext 提供主题上下文
 * @type {React.Context<ThemeContextType>}
 */
export const ThemeContext = createContext<ThemeContextType>({
	darkMode: false,
	setThemeScheme: () => {},
	themeScheme: 'light',
	toggleThemeScheme: () => {}
});

/**
 * icons 根据主题方案提供相应的图标
 * @type {Record<ThemeModeType, string>}
 */
export const icons: Record<ThemeModeType, string> = {
	dark: 'material-symbols:nightlight-rounded',
	light: 'material-symbols:sunny',
	system: 'material-symbols:hdr-auto'
};

/**
 * 切换 CSS 暗模式
 *
 * @param {boolean} darkMode - 是否启用暗模式
 */
export function toggleCssDarkMode(darkMode = false) {
	const htmlElementClassList = document.documentElement.classList;

	if (darkMode) {
		htmlElementClassList.add(DARK_CLASS);
	} else {
		htmlElementClassList.remove(DARK_CLASS);
	}
}

/**
 * 使用主题上下文
 *
 * @returns {ThemeContextType} 当前主题上下文
 * @throws {Error} 如果未在 ThemeProvider 中使用
 */
export function useTheme() {
	const theme = useContext(ThemeContext);

	if (!theme) {
		throw new Error('useTheme must be used within a ThemeProvider');
	}

	return theme;
}
